package chapter8.section7;

/**
 * 利用泛型实现了先进先出的循环队列
 */
public class GenericPool<T> {
    private final Object[] objArray;
    private int headLoc;//
    private int tailLoc;//

    public GenericPool(int length) {
        objArray = new Object[length];
        headLoc = -1;//
        tailLoc = -1;//
    }

    public static void main(String[] args) {
        GenericPool<String> pool = new GenericPool<String>(2);
        System.out.println("1插入位置在" + pool.add("1"));
        System.out.println("2插入位置在" + pool.add("2"));
        String x = pool.get();
        System.out.println("取出了" + x);
        System.out.println("3插入位置在" + pool.add("3"));
        System.out.println("4插入位置在" + pool.add("4"));
    }

    public T get() {
        Object result = null;
        int idx = (headLoc + 1) % objArray.length;// ָ�����һλ
        if (objArray[idx] != null) {
            result = objArray[idx];
            objArray[idx] = null;
            headLoc++;
        }
        return (T) result;
    }

    public int add(T o) {

        int ins = (tailLoc + 1) % objArray.length;
        if (objArray[ins] != null) {
            return -1;
        }
        objArray[ins] = o;
        tailLoc = ins;
        return ins;
    }
}
